package com.good.child.widgets.addressPicker;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.good.child.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Create on: 2024/2/28
 * by Mr.Zhu
 * Description: TODO
 */
public class AreaPickerView  extends Dialog implements DialogInterface.OnDismissListener {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ImageView ivBtn;

    private AreaPickerViewCallback areaPickerViewCallback;
    /**
     * View的集合
     */
    private List<View> views;
    /**
     * tab的集合
     */
    private List<String> strings;
    /**
     * 省
     */
    private List<AddressBean> addressBeans;
    /**
     * 市
     */
    private List<AddressBean> cityBeans;
    /**
     * 区
     */
    private List<AddressBean> areaBeans;

    private Context context;

    private ViewPagerAdapter viewPagerAdapter;
    private AddressAdapter provinceAdapter;
    private AddressAdapter cityAdapter;
    private AddressAdapter areaAdapter;

    /**
     * 选中的区域下标 默认-1
     */
    private int provinceSelected = -1;
    private int citySelected = -1;
    private int areaSelected = -1;

    /**
     * 历史选中的区域下标 默认-1
     */
    private int oldProvinceSelected = -1;
    private int oldCitySelected = -1;
    private int oldAreaSelected = -1;

    private RecyclerView areaRecyclerView;
    private RecyclerView cityRecyclerView;

    private boolean isCreate;
    private int height;

    private DialogInterface.OnDismissListener listener;

    public AreaPickerView(@NonNull Context context, int themeResId, List<AddressBean> addressBeans) {
        super(context, themeResId);
        this.addressBeans = addressBeans;
        this.context = context;
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismiss();
    }

    @Override
    public void setOnDismissListener(@Nullable DialogInterface.OnDismissListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        strings = Arrays.asList("请选择");
        setContentView(R.layout.dialog_area_pickerview);
        Window window = this.getWindow();
        super.setOnDismissListener(this);
        isCreate = true;
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        /**
         * 位于底部
         */
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        if (height > 0) {
            params.height = height;
        }
        window.setAttributes(params);
        /**
         * 设置弹出动画
         */
        window.setWindowAnimations(R.style.PickerAnim);

        tabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.viewpager);
//        ivBtn = findViewById(R.id.iv_btn);
//        ivBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dismiss();
//            }
//        });

        View provinceView = LayoutInflater.from(context)
                .inflate(R.layout.layout_recyclerview, null, false);
        View cityView = LayoutInflater.from(context)
                .inflate(R.layout.layout_recyclerview, null, false);
        View areaView = LayoutInflater.from(context)
                .inflate(R.layout.layout_recyclerview, null, false);

        final RecyclerView provinceRecyclerView = provinceView.findViewById(R.id.recyclerview);
        cityRecyclerView = cityView.findViewById(R.id.recyclerview);
        areaRecyclerView = areaView.findViewById(R.id.recyclerview);

        views = new ArrayList<>();
        views.add(provinceView);
        views.add(cityView);
        views.add(areaView);

        /**
         * 配置adapter
         */
        viewPagerAdapter = new ViewPagerAdapter();
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        /**
         * 这句话设置了过后，假如又3个tab 删除第三个 刷新过后 第二个划第三个会有弹性
         * viewPager.setOffscreenPageLimit(2);
         */

        provinceAdapter = new AddressAdapter(R.layout.item_address, addressBeans);
        provinceRecyclerView.setAdapter(provinceAdapter);
        LinearLayoutManager provinceManager = new LinearLayoutManager(context);
        provinceRecyclerView.setLayoutManager(provinceManager);
        provinceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                cityBeans.clear();
                areaBeans.clear();
                addressBeans.get(position).setStatus(true);
                provinceSelected = position;
                if (oldProvinceSelected != -1 && oldProvinceSelected != provinceSelected) {
                    addressBeans.get(oldProvinceSelected).setStatus(false);
                }
                if (position != oldProvinceSelected) {
                    if (oldCitySelected != -1) {
                        addressBeans.get(oldProvinceSelected).getChildren().get(oldCitySelected).setStatus(false);
                    }
                    if (oldAreaSelected != -1) {
                        addressBeans.get(oldProvinceSelected).getChildren().get(oldCitySelected).getChildren().get(oldAreaSelected).setStatus(false);
                    }
                    oldCitySelected = -1;
                    oldAreaSelected = -1;
                }
                cityBeans.addAll(addressBeans.get(position).getChildren());
                provinceAdapter.notifyDataSetChanged();
                cityAdapter.notifyDataSetChanged();
                areaAdapter.notifyDataSetChanged();
                strings.set(0, addressBeans.get(position).getAreaName());
                if (strings.size() == 1) {
                    strings.add("请选择");
                } else if (strings.size() > 1) {
                    if (position != oldProvinceSelected) {
                        strings.set(1, "请选择");
                        if (strings.size() == 3) {
                            strings.remove(2);
                        }
                    }
                }
                tabLayout.setupWithViewPager(viewPager);
                viewPagerAdapter.notifyDataSetChanged();
                tabLayout.getTabAt(1).select();
                oldProvinceSelected = provinceSelected;
            }
        });

        cityBeans = new ArrayList<>();
        cityAdapter = new AddressAdapter(R.layout.item_address, cityBeans);
        LinearLayoutManager cityListManager = new LinearLayoutManager(context);
        cityRecyclerView.setLayoutManager(cityListManager);
        cityRecyclerView.setAdapter(cityAdapter);
        cityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                areaBeans.clear();
                cityBeans.get(position).setStatus(true);
                citySelected = position;
                if (oldCitySelected != -1 && oldCitySelected != citySelected) {
                    addressBeans.get(oldProvinceSelected).getChildren().get(oldCitySelected).setStatus(false);
                }
                if (position != oldCitySelected) {
                    if (oldAreaSelected != -1 && cityBeans.get(position).getChildren() != null) {
                        addressBeans.get(oldProvinceSelected).getChildren().get(oldCitySelected).getChildren().get(oldAreaSelected).setStatus(false);
                    }
                    oldAreaSelected = -1;
                }
                oldCitySelected = citySelected;
                if (cityBeans.get(position).getChildren() != null) {
                    areaBeans.addAll(cityBeans.get(position).getChildren());
                    cityAdapter.notifyDataSetChanged();
                    areaAdapter.notifyDataSetChanged();
                    strings.set(1, cityBeans.get(position).getAreaName());
                    if (strings.size() == 2) {
                        strings.add("请选择");
                    } else if (strings.size() == 3) {
                        strings.set(2, "请选择");
                    }
                    tabLayout.setupWithViewPager(viewPager);
                    viewPagerAdapter.notifyDataSetChanged();
                    tabLayout.getTabAt(2).select();
                } else {
                    oldAreaSelected = -1;
                    cityAdapter.notifyDataSetChanged();
                    areaAdapter.notifyDataSetChanged();
                    strings.set(1, cityBeans.get(position).getAreaName());
                    tabLayout.setupWithViewPager(viewPager);
                    viewPagerAdapter.notifyDataSetChanged();
                    dismiss();
                    areaPickerViewCallback.callback(provinceAdapter.getItem(oldProvinceSelected), cityAdapter.getItem(oldCitySelected), null);
                }
            }
        });

        areaBeans = new ArrayList<>();
        areaAdapter = new AddressAdapter(R.layout.item_address, areaBeans);
        LinearLayoutManager areaListManager = new LinearLayoutManager(context);
        areaRecyclerView.setLayoutManager(areaListManager);
        areaRecyclerView.setAdapter(areaAdapter);
        areaAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                strings.set(2, areaBeans.get(position).getAreaName());
                tabLayout.setupWithViewPager(viewPager);
                viewPagerAdapter.notifyDataSetChanged();
                areaBeans.get(position).setStatus(true);
                areaSelected = position;
                if (oldAreaSelected != -1 && oldAreaSelected != position) {
                    areaBeans.get(oldAreaSelected).setStatus(false);
                }
                oldAreaSelected = areaSelected;
                areaAdapter.notifyDataSetChanged();
                dismiss();
                areaPickerViewCallback.callback(provinceAdapter.getItem(oldProvinceSelected), cityAdapter.getItem(oldCitySelected),
                        areaAdapter.getItem(areaSelected));
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                switch (i) {
                    case 0:
                        provinceRecyclerView.scrollToPosition(oldProvinceSelected == -1 ? 0 : oldProvinceSelected);
                        break;
                    case 1:
                        cityRecyclerView.scrollToPosition(oldCitySelected == -1 ? 0 : oldCitySelected);
                        break;
                    case 2:
                        areaRecyclerView.scrollToPosition(oldAreaSelected == -1 ? 0 : oldAreaSelected);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (this.addressBeans != null)
            this.addressBeans.clear();
        this.addressBeans = null;
        if (this.areaBeans != null) {
            this.areaBeans.clear();
        }
        this.areaBeans = null;
        if (this.cityBeans != null)
            this.cityBeans.clear();
        this.cityBeans = null;
        if (this.views != null)
            this.views.clear();
        this.views = null;
        if (listener != null)
            listener.onDismiss(dialog);
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return strings.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
            return view == o;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return strings.get(position);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(views.get(position));
        }

    }

    public interface AreaPickerViewCallback {
        void callback(AddressBean province, AddressBean city, AddressBean area);
    }

    public void setAreaPickerViewCallback(AreaPickerViewCallback areaPickerViewCallback) {
        this.areaPickerViewCallback = areaPickerViewCallback;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    private Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 10001:
                    tabLayout.getTabAt(0).view.setEnabled(false);
                    tabLayout.getTabAt(1).view.setEnabled(false);
                    break;

            }
        }
    };

    public void setSelect(String[] selecteds) {
        strings = new ArrayList<>();
        if (selecteds == null) {
            strings.add("请选择");
            if (isCreate) {
                tabLayout.setupWithViewPager(viewPager);
                viewPagerAdapter.notifyDataSetChanged();
                tabLayout.getTabAt(0).select();
                if (provinceSelected != -1)
                    addressBeans.get(provinceSelected).setStatus(false);
                if (citySelected != -1)
                    addressBeans.get(provinceSelected).getChildren().get(citySelected).setStatus(false);
                cityBeans.clear();
                areaBeans.clear();
                provinceAdapter.notifyDataSetChanged();
                cityAdapter.notifyDataSetChanged();
                areaAdapter.notifyDataSetChanged();
            }
            return;
        }
        int provincePoisition = 0, cityPosition = 0;
        if (selecteds.length > 0) {
            strings.add(selecteds[0]);
            provincePoisition = findPositionByLabel(addressBeans, selecteds[0]);
            addressBeans.get(provincePoisition).setStatus(true);
            oldProvinceSelected = provincePoisition;
            if (cityBeans != null) {
                cityBeans.clear();
                cityBeans.addAll(addressBeans.get(provincePoisition).getChildren());
            }
        }
        List<AddressBean> children = null;
        if (selecteds.length > 1) {
            strings.add(selecteds[1]);
            children = addressBeans.get(provincePoisition).getChildren();
            cityPosition = findPositionByLabel(children, selecteds[1]);
            children.get(cityPosition).setStatus(true);

            if (areaBeans != null) {
                areaBeans.clear();
                areaBeans.addAll(addressBeans.get(provincePoisition).getChildren().get(cityPosition).getChildren());
                oldCitySelected = cityPosition;
            }
        }
        if (selecteds.length > 2) {
            if (TextUtils.isEmpty(selecteds[2])) {
                strings.add("请选择");
                List<AddressBean> areaList = children.get(cityPosition).getChildren();
//                int areaPosition = findPositionByLabel(areaList, selecteds[2]);
                oldAreaSelected = 0;
                areaList.get(0).setStatus(true);
                Message message = Message.obtain();
                message.what = 10001;
                handler.sendMessageDelayed(message,1000);

            } else {
                strings.add(selecteds[2]);
                List<AddressBean> areaList = children.get(cityPosition).getChildren();
                int areaPosition = findPositionByLabel(areaList, selecteds[2]);
                oldAreaSelected = areaPosition;
                areaList.get(areaPosition).setStatus(true);
            }

        }
        tabLayout.setupWithViewPager(viewPager);
        viewPagerAdapter.notifyDataSetChanged();
        tabLayout.getTabAt(selecteds.length - 1).select();
        provinceAdapter.notifyDataSetChanged();
        cityAdapter.notifyDataSetChanged();
        areaAdapter.notifyDataSetChanged();
        areaRecyclerView.scrollToPosition(oldAreaSelected == -1 ? 0 : oldAreaSelected);
    }



    int findPositionByLabel(List<AddressBean> beans, String label) {
        if (label == null)
            return -1;
        if (beans != null) {
            final int size = beans.size();
            AddressBean bean;
            for (int i = 0; i < size; i++) {
                bean = beans.get(i);
                if (bean.getAreaName().equals(label))
                    return i;
            }
        }
        return 0;
    }
}


